<template>


  <a-layout>
    <a-layout-sider style="background-color: #fff" >
      <div>
        <a-tree v-if="tree.length" :fieldNames="treeFieldNames" :tree-data="tree"
                :show-line="showLine"
                :show-icon="showIcon"
                @select="selectTree"
                default-expand-all>
        </a-tree>
      </div>
    </a-layout-sider>
    <a-layout>
      <a-layout-content>
        <div>
          <a-card>
            <a-space>
              <a-input
                v-model:value="listQuery.name"
                placeholder="用户姓名搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-input
                v-model:value="listQuery.nickname"
                placeholder="用户昵称搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-input
                v-model:value="listQuery.username"
                placeholder="用户登录名搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-input
                v-model:value="listQuery.phone"
                placeholder="手机号搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-input
                v-model:value="listQuery.email"
                placeholder="邮箱搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-input
                v-model:value="listQuery.source"
                placeholder="来源搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-input
                v-model:value="listQuery.remark"
                placeholder="用户描述搜索"
                allow-clear
                @keyup.enter="handleFilter"
              />
              <a-button type="primary" :icon="h(SearchOutlined)" @click="handleFilter">搜索</a-button>
            </a-space>
          </a-card>
          <a-card class="mt-2">
            <a-button type="primary" class="mb-4" :icon="h(PlusOutlined)" @click="handleAdd">
              添加
            </a-button>
            <a-button type="primary" style="margin-left: 5px" :disabled="!hasSelected" :loading="state.loading" @click="handleDeleteAll">
              批量删除
            </a-button>

            <a-table
              bordered
              :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
              :columns="columns"
              :data-source="data"
              :pagination="pagination"
              :loading="tableLoading"
              :scroll="{ x: 1800 }" :expand-column-width="100"
              :row-key="(row) => row.ssoUserId + ''"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'avatar'">
                  <div style="display: flex;align-items: center;">
                  <div><a-avatar :size="30" :src="record.avatar" ></a-avatar></div>
                  <div style="margin-left:5px ">{{record.username}}</div>
                  </div>
                </template>
                <template v-if="column.dataIndex === 'ssoOrganization'">
                  <a-tag color="#108ee9" v-if="record.ssoOrganization">{{ record.ssoOrganization.name }}</a-tag>
                  <a-tag color="#f50" v-else>无组织</a-tag>
                </template>
                <template v-if="column.dataIndex === 'job'">
                  <div v-if="record.jobs&&record.jobs.length>0" v-for="(item) in record.jobs">
                      <a-tag color="#34bee9" style="margin: 2px">
                        {{ item.name }}
                      </a-tag>
                  </div>
                  <a-tag color="#f50" v-else>无职位</a-tag>
                </template>
                <template v-if="column.dataIndex === 'locked'">
                  <a-tag color="#87d068" v-if="record.locked==0||record.locked==null">启用</a-tag>
                  <a-tag color="#f50" v-else>冻结</a-tag>
                </template>

                <template v-if="column.dataIndex === 'actions'">
                  <a-button size="small" type="link" @click="handleEdit(record)">编辑</a-button>
                  <a-button size="small" type="link" danger @click="handleDelete(record)">删除</a-button>
                </template>
              </template>
            </a-table>
          </a-card>
          <a-modal v-model:open="showModal" :mask-closable="false" :title="title">
            <a-form
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 5 }"
              style="padding-top: 20px"
            >

              <a-form-item label="组织选择" name="ssoOrganizationId">
                <a-tree-select
                  v-model:value="form.ssoOrganizationId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="tree"
                  :fieldNames="treeFieldNames2"
                >
                </a-tree-select>
                <template #title="{ name }">
                  <span>{{ name }}</span>
                </template>
              </a-form-item>



              <a-form-item label="职位选择" name="jobIds">
                <a-select
                  v-model:value="form.jobIds"
                  show-search
                  placeholder="职位关键字"
                  mode="multiple"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  :options="jobsData"
                  @search="handleSearch"
                  @change="handleChange"
                ></a-select>
              </a-form-item>

              <a-form-item label="头像" name="avatar">
                <a-upload
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  :action="beforeUpload"
                >
                  <img v-if="form.avatar" style="height: 80px;width: 80px;" :src="form.avatar" alt="avatar" />
                  <div v-else>
                    <loading-outlined v-if="loading"></loading-outlined>
                    <plus-outlined v-else></plus-outlined>
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
              </a-form-item>
              <a-form-item label="用户姓名" name="name">
                <a-input v-model:value="form.name" allow-clear placeholder="请输入用户姓名" />
              </a-form-item>
              <a-form-item label="用户昵称" name="nickname">
                <a-input v-model:value="form.nickname" allow-clear placeholder="请输入用户昵称" />
              </a-form-item>
              <a-form-item label="用户登录名" name="username">
                <a-input v-model:value="form.username" allow-clear placeholder="请输入用户登录名" />
              </a-form-item>
              <a-form-item label="密码" name="password">
                <a-input v-model:value="form.password" allow-clear placeholder="请输入密码" />
              </a-form-item>
              <a-form-item label="手机号" name="phone">
                <a-input v-model:value="form.phone" allow-clear placeholder="请输入手机号" />
              </a-form-item>
              <a-form-item label="邮箱" name="email">
                <a-input v-model:value="form.email" allow-clear placeholder="请输入邮箱" />
              </a-form-item>
              <a-form-item label="来源" name="source">
                <a-input v-model:value="form.source" allow-clear placeholder="请输入来源" />
              </a-form-item>
              <a-form-item label="用户状态" name="ssoAppGroupId">
                <a-select
                  v-model:value="form.locked"
                  show-search
                  placeholder="请选择状态"
                  option-filter-prop="label"
                  :options="statusOption"
                />
              </a-form-item>
              <a-form-item label="用户描述" name="remark">
                <a-input v-model:value="form.remark" allow-clear placeholder="请输入用户描述" />
              </a-form-item>
            </a-form>
            <template #footer>
              <a-button type="primary" :loading="formBtnLoading" @click="handleConfirm">提交</a-button>
            </template>
          </a-modal>
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout>


</template>

<script setup lang="ts">
import {computed, h, onMounted, reactive, ref, watch} from 'vue';
import SsoUserApi from '@/api/SsoUserApi';
import { PlusOutlined, SearchOutlined,LoadingOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { Rule } from 'ant-design-vue/es/form';
import { resetReactive } from '@/utils';
import SsoOrganizationApi from "@/api/SsoOrganizationApi";
import {Key} from "node:readline";
import SsoJobApi from "@/api/SsoJobApi";
import ResApi from "@/api/Res";
const showLine = ref<boolean>(true);
const showIcon = ref<boolean>(false );

const treeFieldNames = ref(	{children:'children', title:'name', key:'ssoOrganizationId' })
const treeFieldNames2 = ref(	{children:'children', label:'name', value:'ssoOrganizationId' })

let columns = [
  { title: '用户账号', dataIndex: 'avatar' ,ellipsis: true   ,fixed: 'left',},
  { title: '用户姓名', dataIndex: 'name' ,ellipsis: true},
  { title: '用户昵称', dataIndex: 'nickname'  ,ellipsis: true},
  { title: '用户组织', dataIndex: 'ssoOrganization'  ,ellipsis: true},
  { title: '用户职位', dataIndex: 'job'  ,ellipsis: true},
  { title: '手机号', dataIndex: 'phone' ,ellipsis: true },
  { title: '邮箱', dataIndex: 'email'  ,ellipsis: true},
  { title: '来源', dataIndex: 'source' ,ellipsis: true },
  { title: '冻结', dataIndex: 'locked'  ,ellipsis: true},
  { title: '描述', dataIndex: 'remark'  ,ellipsis: true},
  { title: '创建时间', dataIndex: 'createTime' },
  { title: '更新时间', dataIndex: 'updateTime' },
  {
    title: '操作',
    dataIndex: 'actions',
    align: 'center',
    fixed: 'right',
  },
];
let tree = ref([]);
let data = ref([]);
const jobsData = ref([]);

const loading=ref(false)

let timeout: any;
let currentValue = null;
function fetch(value: string, callback: any) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  function fake() {
    SsoJobApi.list({name:value}).then(res=>{
      if (currentValue === value) {
        console.log(res)
        const result = res.data;
        const data: any[] = [];
        result.forEach((r: any) => {
          data.push({
            value: r.id,
            label: r.name,
          });
        });
        console.log(data)
        callback(data);
      }
    })
  }
  timeout = setTimeout(fake, 300);
}

const handleSearch = (val: string) => {
  fetch(val, (d: any[]) => (jobsData.value = d));
};
const handleChange = (val: string) => {
  form.jobIds = val;
  fetch(val, (d: any[]) => (jobsData.value = d));
};



const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (current, pageSize) => {
    pagination.current = current;
    pagination.pageSize = pageSize;
    getList();
  },
});

const state = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
});

const hasSelected = computed(() => state.selectedRowKeys.length > 0);
const onSelectChange = (selectedRowKeys: Key[]) => {
  console.log(selectedRowKeys)
  state.selectedRowKeys = selectedRowKeys;
};

const statusOption=[
  {
    value: 0,
    label: '启用',
  },
  {
    value: 1,
    label: '禁用',
  },
]

onMounted(() => {
  getList();
  getOrganization();
});

const listQuery = reactive<any>({});
const tableLoading = ref(false);
const selectTree = (selectedKeys, e)=>{
  if (e.selected){
    let ids=[e.node.ssoOrganizationId]
    if (e.node.dataRef.children){
      let d =   e.node.dataRef.children.map(k=>{
        return k.ssoOrganizationId
      })
      ids.push(...d)
    }
    listQuery.organizationIds=ids;
  }else{
    listQuery.organizationIds=[];
  }
  pagination.current=1
  getList()
}
function getList() {
  tableLoading.value = true;
  SsoUserApi.page({ index: pagination.current, size: pagination.pageSize, ...listQuery })
    .then((res) => {
      data.value = res.data;
      pagination.total = res.total;
    })
    .finally(() => (tableLoading.value = false));
}

const getOrganization = ()=>{
  SsoOrganizationApi.getListTree().then(res=>{
    tree.value = res.data[0].tree;
  })
}


function handleFilter() {
  pagination.current = 1;
  getList();
}

const showModal = ref(false);
const title = ref('');
const formRef = ref();
let form = reactive<any>({});
const rules: Record<string, Rule[]> = {
  name: [{ required: true, trigger: 'blur', message: '请输入' }],
  jobIds: [{ required: true, trigger: 'blur', message: '请输入' }],
  nickname: [{ required: true, trigger: 'blur', message: '请输入' }],
  password: [{ required: true, trigger: 'blur', message: '请输入' }],
  username: [{ required: true, trigger: 'blur', message: '请输入' }],
  ssoOrganizationId: [{ required: true, trigger: 'blur', message: '请选择' }],
};

function handleEdit(row) {
  showModal.value = true;
  title.value = '编辑';
  Object.assign(form, row);
  //设置jobs到jobIds
  form.jobIds=[]
  if (row.jobs&&row.jobs.length>0){
    for (let item of row.jobs){
      form.jobIds.push(item.id)
    }
    handleSearch(form.jobIds)
  }
  console.log(form)
  formRef.value?.clearValidate();
}

function handleAdd() {
  showModal.value = true;
  title.value = '添加';
  resetReactive(form);
  formRef.value?.clearValidate();
}

const formBtnLoading = ref(false);

function handleConfirm() {
  formRef.value
    .validate()
    .then(() => {
      formBtnLoading.value = true;
      (form.ssoUserId ? SsoUserApi.update(form) : SsoUserApi.save(form))
        .then(() => {
          message.success('提交成功');
          showModal.value = false;
          getList();
        })
        .finally(() => {
          formBtnLoading.value = false;
        });
    })
    .catch(() => {});
}

function handleDelete(row) {
  Modal.confirm({
    title: '提示',
    content: '确定删除这条记录吗',
    onOk() {
      SsoUserApi.delete([row.ssoUserId]).then(() => {
        message.success('操作成功');
        getList();
      });
    },
    onCancel() {},
  });
}
function handleDeleteAll() {
  Modal.confirm({
    title: '提示',
    content: '确定删除这这些记录吗',
    onOk() {
      SsoUserApi.delete(state.selectedRowKeys).then(() => {
        message.success('操作成功');
        getList();
      });
    },
    onCancel() {},
  });
}
function beforeUpload(file){
 loading.value=true
  ResApi.upLoad(file).then(res=>{
    console.log(res)
    if (res.code==="SUCCESS"){
     form.avatar=res.data[0]
    }

  }).finally(()=>{
    loading.value=false
  })
}


</script>

<style scoped></style>
